﻿//#include <QtCore>
//#include <QImage>
//#include <QJsonObject>
//#include <QSettings>
//#include <QByteArray>

#include<QtWidgets/QApplication>
#include<QtWidgets/QPushButton>
#include<QtCore/QtPlugin>
#include <QtCore/QSettings> 
#include <QtCore/QTextCodec>
#include <QtCore/QTranslator>
#include <QtCore/QJsonObject> 
//#include <QtCore/QByteArray>

#include "HttpServer.h"
#include "easylogging++.h"

#include "DBService.h"
#include "ThreadManger.h"
#include "WorkThread.h"
#include "OutPutMessage.h"



INITIALIZE_EASYLOGGINGPP

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

	int iListenPort = 0;
	int iListenThread = 0;
	int iWorkThread = 0;
	QString strLogFile;
	QString strTransFile;
    QString strPluginsDir;

	//读取配置文件
	QString appFile = QCoreApplication::applicationDirPath() + "/" + QCoreApplication::applicationName() + ".ini";
	QSettings config(appFile, QSettings::IniFormat);

	config.beginGroup("SERVER");
	iListenPort = config.value("ListenPort", 0).toInt();
	iListenThread = config.value("ListenThread", 1).toInt();
	iWorkThread = config.value("WorkThread", 1).toInt();
	strLogFile = QCoreApplication::applicationDirPath() + "/" + config.value("Log", "log.conf").toString();
	strTransFile = QCoreApplication::applicationDirPath() + "/" + config.value("Lang", "httpserver_zh.qm").toString();
    strPluginsDir = QCoreApplication::applicationDirPath() + "/" + config.value("Plugins", "plugins").toString();
    QByteArray codec = config.value("LocaleCodec", "GB18030").toString().toLocal8Bit();
    QTextCodec::setCodecForLocale(QTextCodec::codecForName(codec));
    config.endGroup();

	//设置翻译
	QTranslator * translator = new QTranslator(0);
	translator->load(strTransFile);
	qApp->installTranslator(translator);

    //Load DB Driver
    a.addLibraryPath(strPluginsDir);

	//设置日志
	el::Loggers::addFlag(el::LoggingFlag::StrictLogFileSizeCheck);
	QByteArray arrLogFile = strLogFile.toLocal8Bit();
	el::Configurations conf(arrLogFile.data());
	el::Loggers::reconfigureAllLoggers(conf);

	if (iListenPort == 0)
	{
		QString strError = QObject::tr("Listen port is 0, please set listen port!");
		outPutMessage(strError, MSG_ERROR);
		return 0;
	}

	ThreadManger::initThreadManger(iWorkThread);
    TcpServerManage tcpServerManage( iListenThread ); 
    tcpServerManage.setHttpAcceptedCallback( []( const QPointer< Session > &session )
    {
        // 回调发生在新的线程内，不是主线程，请注意线程安全
        // 若阻塞了此回调，那么新的连接将不会得到处理（默认情况下有2个线程可以阻塞2次，第3个连接将不会被处理）
		const QString & strUrl = session->requestUrl();
		const QByteArray & strRequest = session->requestRawData();
		WorkThread * pWork = ThreadManger::getMinPayThread();

		if (pWork)
		{
            const QJsonObject & data = pWork->requestData(strUrl, strRequest);
			session->replyJsonObject(data);
		}
		else
		{
			QJsonObject data;
			data.insert("Error", "Not found Work Thread!");
			session->replyJsonObject(data);
		}
		
    } );

	bool bListen = tcpServerManage.listen(QHostAddress::Any, iListenPort);
	if (!bListen)
	{
		QString strError = QObject::tr("Listen failed on port: %1, Please check port is enable").arg(iListenPort);
		outPutMessage(strError, MSG_ERROR);
		return 0;
	}

	QString strInfo = QObject::tr("listen on port: %1  true").arg(iListenPort);
	outPutMessage(strInfo);
	QThread * pThread = new QThread;
	tcpServerManage.moveToThread(pThread);
    return a.exec();
}
